package com.ruitu.mall_98_seller.ui.home;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.arad.util.UIUtils;
import com.ruitu.mall_98_seller.R;
import com.ruitu.mall_98_seller.base.MyApp;
import com.ruitu.mall_98_seller.dao.bean.HomeNum;
import com.ruitu.mall_98_seller.mvp.model.HomeModel;
import com.ruitu.mall_98_seller.mvp.presenter.HomePresenter;
import com.ruitu.mall_98_seller.ui.book.BookListActivity;
import com.ruitu.mall_98_seller.ui.order.OrderListActivity;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.Config;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.Version;
import com.ruitu.router_module.util.AlertUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import me.jessyan.progressmanager.ProgressListener;
import me.jessyan.progressmanager.ProgressManager;
import me.jessyan.progressmanager.body.ProgressInfo;

public class WorkFragment extends BaseFragment<HomePresenter.HomeP, HomeModel.HomeM> implements HandlerUtil.OnReceiveMessageListener {
    private TextView tv_title;
    private TextView tv_all_order;// 查看全部
    private RelativeLayout rl_sta_1, rl_sta_2, rl_sta_3, rl_sta_4;
    private RelativeLayout rl_model_1, rl_model_2, rl_model_3, rl_model_4;// 订单管理,预订审批,消息,商品管理
    private TextView tv_yester_in, tv_seven_in;
    private TextView tv_num_1, tv_num_2, tv_num_3, tv_num_4;

    HandlerUtil.HandlerHolder handlerHolder;

    public static WorkFragment newInstance() {
        Bundle args = new Bundle();
        WorkFragment fragment = new WorkFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handlerHolder = new HandlerUtil.HandlerHolder(this);
        Arad.bus.register(this);
    }

    private boolean isDestroy = false;

    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestroy = true;
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
        p.startMyThread(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetBusMsg(EventModel ev) {
        if (ev.getEventCode() == 19090551) {// 检查新版本
            rxList.add(p.reqNewVersion("2", true));
        }
        if (ev.getEventCode() == 19090651) {// 登录成功,获取各种数量
            if (CommonUtils.isLogin()) {// 根据企业id获取各种数量
                p.reqHomeNums(AppHolder.instance().getUser().getCompany().getId());
            } else {
                tv_num_1.setText("0");
                tv_num_2.setText("0");
                tv_num_3.setText("0");
                tv_num_4.setText("0");
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_work, container, false);
        tv_all_order = v.findViewById(R.id.tv_all_order);
        tv_title = v.findViewById(R.id.tv_title);
        rl_model_1 = v.findViewById(R.id.rl_model_1);
        rl_model_2 = v.findViewById(R.id.rl_model_2);
        rl_model_3 = v.findViewById(R.id.rl_model_3);
        rl_model_4 = v.findViewById(R.id.rl_model_4);
        tv_yester_in = v.findViewById(R.id.tv_yester_in);
        tv_seven_in = v.findViewById(R.id.tv_seven_in);
        tv_num_1 = v.findViewById(R.id.tv_num_1);
        tv_num_2 = v.findViewById(R.id.tv_num_2);
        tv_num_3 = v.findViewById(R.id.tv_num_3);
        tv_num_4 = v.findViewById(R.id.tv_num_4);
        rl_sta_1 = v.findViewById(R.id.rl_sta_1);
        rl_sta_2 = v.findViewById(R.id.rl_sta_2);
        rl_sta_3 = v.findViewById(R.id.rl_sta_3);
        rl_sta_4 = v.findViewById(R.id.rl_sta_4);

        tv_title.setText("工作台");
        setOnClickListener(tv_all_order, rl_model_1, rl_model_2, rl_model_3, rl_model_4, rl_sta_1, rl_sta_2, rl_sta_3, rl_sta_4);
        alertDialog = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();

        rxList.add(p.reqNewVersion("2", false));

        return v;
    }

    @Override
    public void onClick(View v) {
        if (v == tv_all_order || v == rl_model_1) {
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(OrderListActivity.class);
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == rl_model_2) {// 预订单管理,审批
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(BookListActivity.class);
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == rl_model_3) {// 切换到消息页面
            ((HomeActivity) getActivity()).setNavigationPage(1);
        }
        if (v == rl_sta_1) {// 订单状态1
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(OrderListActivity.class, genBundle("2"));
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == rl_model_4) {// 商品管理
            ToastUtils.showShortSafe("敬请期待");
//            JPushInterface.getAlias(Arad.app, AppHolder.instance().getSequence());
//            Logg.i(JPushInterface.isPushStopped(Arad.app) ? "极光已停止..." : "极光运行中...");
        }
        if (v == rl_sta_2) {// 订单状态2
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(OrderListActivity.class, genBundle("4"));
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == rl_sta_3) {// 订单状态3
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(OrderListActivity.class, genBundle("7"));
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
        if (v == rl_sta_4) {// 订单状态4
            if (CommonUtils.isLoginToActivity(getActivity())) {
                startActivity(OrderListActivity.class, genBundle("6"));
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
        }
    }

    private Bundle genBundle(String status) {
        Bundle bundle = new Bundle();
        bundle.putString("status", status);
        return bundle;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (CommonUtils.isLogin()) {// 根据企业id获取各种数量
            p.reqHomeNums(AppHolder.instance().getUser().getCompany().getId());
        }
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {// 获取首页各种数量
            HomeNum num = (HomeNum) data;
            if (null != num) {
                tv_yester_in.setText("￥" + num.getCountTodaySales());
                tv_seven_in.setText("￥" + num.getCount7Sales());
                tv_num_1.setText(num.getCountPendingSend());
                tv_num_2.setText(num.getCountPendingCollect());
                tv_num_3.setText(num.getCountComplete());
                tv_num_4.setText(num.getCountAfterSale());
            }
        }
        if (code == 2) {// 新版本
            Version ver = (Version) data;
            url = Config.BASE_URL + ver.getUrl();
            Logg.i("url = " + url);
            //Okhttp/Retofit 下载监听
            ProgressManager.getInstance().addResponseListener(url, listener);
            UIUtils.showAlertDialog(getChildFragmentManager(), "发现新版本"
                    , "本次更新内容：\n" + ver.getContent() + "\n是否更新？",
                    "更新", "取消"
                    , new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            p.downloadApk(MyApp.getOkHttpClient(), url);
                            if (!isDestroy) {
                                showDialog();
                            }
                        }
                    }, null);
        }
    }

    String url;
    private int progress = 0;

    private ProgressListener listener = new ProgressListener() {
        @Override
        public void onProgress(ProgressInfo progressInfo) {
            progress = progressInfo.getPercent();

            if (progress % 10 == 0) {
                Logg.i("--Download-- " + progress + " %  " + progressInfo.getSpeed() + " byte/s  " + progressInfo.toString());
            }

            handlerHolder.sendEmptyMessage(19090352);
            if (progressInfo.isFinish()) {// 下载完成
                Logg.i("--Download-- finish");
                handlerHolder.sendEmptyMessage(19090353);
            }
        }

        @Override
        public void onError(long id, Exception e) {
            handlerHolder.sendEmptyMessage(19090351);
        }
    };

    private ProgressBar progressBar;
    private TextView tv_ok, tv_progress;
    private AlertDialog alertDialog;
    private View alert_view;//对话框的布局

    // 弹窗
    private void showDialog() {
        alert_view = View.inflate(getActivity(), R.layout.alert_download_porgress, null);
        alertDialog.show();
        AlertUtil.setAlertCenterStyle(alertDialog.getWindow(), alert_view, getActivity());

        progressBar = alert_view.findViewById(R.id.progress_bar);
        tv_ok = alert_view.findViewById(R.id.tv_ok);
        tv_progress = alert_view.findViewById(R.id.tv_progress);

        progressBar.setMax(100);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (progress < 100) {
                    ToastUtils.showShortSafe("下载中,请稍候");
                    return;
                }
                alertDialog.dismiss();
                p.installApp(getActivity(), new File(getActivity().getExternalCacheDir() + "/seller.apk"));
            }
        });
        alert_view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                p.startMyThread(false);
            }
        });

        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        alertDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 19090351) {
            if (!isDestroy) {
                alertDialog.dismiss();
            }
            ToastUtils.showShortSafe("下载已取消");
        } else if (msg.what == 19090352) {
            if (!isDestroy) {
                tv_progress.setText(progress + "%");
                progressBar.setProgress(progress);
                if (progress < 100) {
                    tv_ok.setEnabled(false);
                } else if (progress == 100) {
                    tv_ok.setEnabled(true);
                    tv_progress.setText("完成");
                }
            }
        } else if (msg.what == 19090353) {
            if (!isDestroy) {
                tv_ok.setEnabled(true);
                tv_progress.setText("完成");
            }
        }
    }
}
